<?php
namespace Utuo;

use My\Model\UserRole;
use My\Model\WechatUserModel;

class WechatUserLogin {
	
	
	/**
	 * 登录时间SESSION键名
	 * @var unknown
	 */
	const LOGIN_TIME = '_login_time_';
	
	/**
	 * 登录用户sessionKey
	 * @var unknown
	 */
	const USER_SESSION_KEY = "wechat_user";
	
	/**
	 * 登录超时时间 0.长期有效
	 * @var unknown
	 */
	const LOGIN_EXPIRES = 0;
	
	
	/**
	 * 用户数据
	 * @var unknown
	 */
	public $data = array();
	
	/**
	 * 
	 */
	public $wechatConfig = array();
	
	/**
	 * 微信高级接口
	 * @var unknown
	 */
	protected $wechatAdvance;
	
	/**
	 * 用户真实key
	 * @var unknown
	 */
	protected $sessionKey;
	
	/**
	 * 客户id
	 * @var unknown
	 */
	protected $cid;
	
	/**
	 * 获得实例
	 * @return Ambigous <NULL, \Utuo\WechatUserLogin>
	 */
	public static function newInstance( $config ) {
		static $object = null;
		if ( !$object ) {
			$object = new WechatUserLogin( $config );
		}
		return $object;
	}
	
	/**
	 * 构造
	 * @param unknown $config
	 */
	public function __construct( $config ) {
		$this->cid = $config['cid'];
		$this->sessionKey = self::USER_SESSION_KEY.'_'.$this->cid;
		$this->wechatAdvance = $config['wechatAdvance'];
		$this->wechatConfig = M('Wechat')->where("cid=%d", $this->cid)->find();
		session("sessionKey", $this->sessionKey);
	}
	
	/**
	 * 增加与更新微信用户信息
	 *
	 * @param unknown $openId
	 */
	public function refreshWechatUser($openId = 0, $user) {
		$openId or $openId = $this->openId;
		if( !$openId ) {
			return false;
		}
		$globalTokenRes = $this->wechatAdvance->getBaseAccess();
		if (false != $globalTokenRes) {
			$accessToken = $globalTokenRes['access_token'];
			$info = $this->wechatAdvance->getUserInfo($accessToken, $openId);
			if (false !== $info) {
				$userInfo = $this->bindUser(array (
						'cid' => $this->cid,
						'openId' => $openId,
						'isNew' => $user['isNew'],  // 是否新插入用户为true时可对用户信息直接更新
				), $info);
				return $userInfo;
			}
		}
		return $this->bindUser(array (
				'cid' => $this->cid,
				'openId' => $openId
		)); // 未更新获得当前已绑定的信息
	}
	
	/**
	 * 设置登录
	 *
	 * @param array $user array(
	 *        'id' => 1,
	 *        'mid' => 3,
	 *        'nickname'=> '',
	 *        'face'=> '',
	 *        )
	 */
	public function setLogin($user) {
		/* 保存用户session */
		session($this->sessionKey, array (
			'id' => $user['id'],
			'mid' => $user['mid'],
			'nickname' => $user['nickname'],
			'face' => $user['face'],
			'subscribe' => $user['subscribe'],
			'debug' => $user['debug'],
			'type' => $user['type'],
		));
		$this->sessionKeys = array (
			'id',
			self::LOGIN_TIME
		);
		session('id', $user['id']);
		session(self::LOGIN_TIME, NOW_TIME);
		session("sessionKeys", serialize($this->sessionKeys));
		/* 保存用户在系统的登录信息 */
		$adminData = array (
				'lastLoginTime' => NOW_TIME,
				'lastLoginIp' => get_client_ip(),
				'loginCount' => $user['loginCount'] + 1
		);
		M('WechatUser')->where("id=" . $user['id'])->save($adminData);
		$this->getLogin();
	}
	
	/**
	 * 退出
	 *
	 * @return \Utuo\DistributionShopForeground
	 */
	public function setLogout() {
		session($this->sessionKey, null);
		if (session("sessionKeys"))
			$this->sessionKeys = unserialize(session("sessionKeys"));
		else
			$this->sessionKeys = array ();
		foreach ($this->sessionKeys as $name) {
			session($name, null);
		}
		return $this;
	}
	
	/**
	 * 获得session用户信息
	 *
	 * @see \Utuo\ForegroundController::getLogin()
	 */
	public function getLogin() {
		$user = session($this->sessionKey);
		$this->data = $user ? $user : array();
		return $user;
	}
	
	
	/**
	 * 检查登录
	 */
	public function checkLogin() {
		$isLogined = true;
		$loginTime = session(self::LOGIN_TIME);
		$user = $this->getLogin();
		if ( $user and !$user['subscribe'] and (NOW_TIME - $loginTime * 1) > 10 ) { // 未关注十秒一检查关注
			$isLogined = false;
			$this->setLogout();
		} elseif ( self::LOGIN_EXPIRES and $user['id'] and (NOW_TIME - $loginTime * 1) > self::LOGIN_EXPIRES ) { // 检查登录超时
			$isLogined = false;
			$this->setLogout();
		} elseif ( !$user or !$user['id'] or !$loginTime )  { // 未登录
			$isLogined = false;
			$this->setLogout();
		}
		return $isLogined;
	}
	
	
	/**
	 * 添加与更新微信用户
	 *
	 * @param unknown $cid 客户id
	 * @param unknown $param 用户信息
	 * array(
	 *  'mid' => 0,
	 *  'openId' => 'oIoTWjua2ih8sgLaW-YJzRWy_2IM',
	 * )
	 * @param array $info 用户扩展信息(参考微信返回用户信息接口)
	 * array(
	 * 	'nickname' => '简单快乐',
	 *  'headimgurl' => '',
	 * )
	 * @return array(id,mid,cid,openId,face,nickname,subscribe[,loginCount])
	 */
	public function bindUser($param, $info = array()) {
		$openId = $param['openId'];
		$qid = empty($param['qid']) ? 0 : $param['qid'];
		$isNew = empty($param['isNew']) ? 0 : 1;
		DBRW::openAndClose(0);
		$wechatUser = M("WechatUser")->where(array (
				'cid' => $this->cid,
				'openId' => $openId,
		))->find();
		DBRW::openAndClose(1);
		if ( !$wechatUser and !$isNew ) { // 添加(刚插入数据可能无法查到用$param['isNew']再次判断)
			/*获得师傅信息*/
			$mid = isset($param['mid']) ? $param['mid'] : 0; // 师傅id
			DBRW::openAndClose(0);
			$masterWechatUser = M("WechatUser a")->join("__DISTRIBUTION_SHOP_USER_TREE__ b on a.id=b.uid", "LEFT")->where("a.cid=%d and a.id=%d", $this->cid, $mid)->field("a.*,b.tree,SUBSTRING_INDEX(b.tree,',',-1) as topId")->find(); // 师傅信息
			DBRW::openAndClose(1);
			if ( !$masterWechatUser ) {
				$mid = 0;
			} else {
				$tree = $masterWechatUser['tree'];
				$topId = $masterWechatUser['topId'];
			}
			/*添加用户基础数据*/
			$userRole = new UserRole();
			$addWechatUser = array (
					'mid' => $mid,
					'cid' => $this->cid,
					'qid' => $qid,
					'openId' => $openId,
					'createTime' => time(),
					'type' => $userRole->becomeTo(WechatUserModel::USER_TYPE_STANDARD)->getType(),
			);
			/*所属代理*/
			$agent = null;
			if ( $mid ) {
			    $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $this->cid, $mid)->find();
			    if ( $agent ) {
			        $addWechatUser['tmpAid'] = $agent['id'];
			    }
			}
			/*添加用户扩展数据*/
			if ( $info ) {
				$addWechatUser['face'] = isset($info['headimgurl']) ? $info['headimgurl'] : '';
				$addWechatUser['nickname'] = isset($info['nickname']) ? $info['nickname'] : '';
				$addWechatUser['subscribe'] = isset($info['subscribe']) ? $info['subscribe'] : 0;
			}
			$newId = M("WechatUser")->add($addWechatUser);
				
			if ( $newId ) {
				/* 添加用户后的后续处理 */
				$addWechatUser['id'] = $newId;
				$accessTokenArray = $this->wechatAdvance->getBaseAccess();
				$disShop = M("DistributionShop")->where(array('cid'=>$this->cid))->find();
				$count = M("WechatUser")->where('cid=%d', $this->cid)->count();
				/* 保存师徒关系树 */
				$tree = $masterWechatUser['tree'];
				if ( $mid ) {
				    $tree = $newId . ',' . $tree; // 新增用户的用户树
				    // 师傅的徒弟数加一
				    M("WechatUser")->where('id=%d', $mid)->setInc('sonCount', 1);
				    // 徒弟的师傅字符串
				    M('WechatUser')->where(array ('id' => array ('in', $masterWechatUser['tree'] )))->setInc('subCount', 1); // 所有上级的sub_count加一
				} else {
				    $tree = $newId;
				}
			    M("DistributionShopUserTree")->add(array(
				    'uid' => $newId,
				    'cid' => $this->cid,
				    'tree' => $tree,
				    'length' => count(explode(',', $tree)),
			    ));
			    		
			    /* 发送消息 */
				if ( $mid ) { // 有师
					isset($topId) and $topWechatUser = M("WechatUser")->where(array ('id' => $topId,))->field('subCount,openId')->find();
					// 向关注人发送客服消息的内容
					if ( !empty($addWechatUser['nickname']) ) {
    					$data = array(
    						"articles" => array(
    								array(
    									'title' => sprintf("亲爱的  %s 您好：", $addWechatUser['nickname']),
    									'description' => sprintf("恭喜您由【 %s】推荐成为【%s】的第【%d】位会员。\n%s", $masterWechatUser['nickname'], $disShop['name'], $count + 1, $disShop['subscribe_info']),
    									'url' => '',
    								)
    						)
    					);
					}
					// 向最顶端推送模板消息
					isset($topWechatUser) and $this->sendAddMsg(array('newId'=>$newId, 'subCount'=>$topWechatUser['subCount']+1), $accessTokenArray['access_token'], $topWechatUser['openId']);
					if( $topId != $mid ) {
						// 向师傅发送模板消息
						$this->sendAddMsg(array('newId'=>$newId, 'subCount'=>$masterWechatUser['subCount']+1), $accessTokenArray['access_token'], $masterWechatUser['openId']);
					}
				} else { // 无师
					// 向关注人发送客服消息的内容
				    if ( !empty($addWechatUser['nickname']) ) {
				        $data = array(
				            "articles" => array(
				                array(
				                    'title' => sprintf("亲爱的  %s 您好：", $addWechatUser['nickname']),
				                    'description' => sprintf("恭喜您已成为【%s】的第【%d】位会员。\n%s", $disShop['name'], $count + 1, $disShop['description']),
				                    'url' => '',
				                )
				            )
				        );
				    }
				}
				isset($data) and $this->wechatAdvance->sendServerMessage( $accessTokenArray['access_token'], $openId, $data, 5 );
				$addWechatUser["isNew"] = 1;
				return $addWechatUser;
			}
		} else {
		    $mid = isset($param['mid']) ? $param['mid'] : 0; // 师傅id
		    $data = array();
			if ( $info ) {
			    $data['nickname'] = $info['nickname'];
			    $data['face'] = $info['headimgurl'];
				if ( $info['subscribe'] ) { // 已关注时
				    $data['subscribe'] = 1;
				} else { // 未关注时
					$data['subscribe'] = 0;
				}
			}
			/* 关注时间 */
			if ( isset($param['subscribeTime']) ) {
			    $data['subscribeTime'] = $param['subscribeTime'];
			}
			/* 所属代理 */
			$agent = null;
			if ( $mid ) {
			    $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $this->cid, $mid)->find() and $data['tmpAid'] = $agent['id'];
			}
			/* 更新用户信息 */
		    $wechatUser = array_merge($wechatUser, $data);
		    if( M("WechatUser")->where(array('id' => $wechatUser['id']))->save($data) ) {
		        $wechatUser["isFresh"] = 1;
		    }
			return $wechatUser;
		}
		return false;
	}
	
	/**
	 * 发送加入消息
	 * @param array $param
	 * array(
	 * 	newId,subCount
	 * )
	 */
	protected function sendAddMsg($param, $accessToken, $openId) {
	    $result = false;
		$templateId = isset($this->wechatConfig['templateid']) ? $this->wechatConfig['templateid'] : null; // "OtEPSHE5NbL6YHT9v4ElTmsbvb6LTq5I2VRLb7lyAcs";
		$templateType = isset($this->wechatConfig['templateType']) ? $this->wechatConfig['templateType'] : 1;
		if ( $templateType == 1 ) {
			$data = array (
					'first' => array (
							'value' => "恭喜，你有新的朋友加入！",
							'color' => '#0000ee'
					),
					'infotitle' => array (
							'value' => "您有一个新的朋友加入",
							'color' => "#ee0000"
					),
					'infoId' => array (
							'value' => str_pad($param['newId'], 6, '0', STR_PAD_LEFT),
							'color' => '#ee0000'
					),
					'statusType' => array (
							'value' => '会员总数',
							'color' => '#000000',
					),
					'status' => array (
							'value' => '共有会员'.$param['subCount'].'位',
							'color' => '#ee0000'
					),
					'remark' => array (
							'value' => '继续加油，邀请更多的朋友们加入吧~~',
							'color' => '#999999'
					)
			);
		} elseif ( $templateType == 2 ) {
			$data = array (
					'first' => array (
							'value' => "恭喜，你有新的朋友加入！",
							'color' => '#0000ee'
					),
					'schedule' => array (
							'value' => "您有一个新的朋友加入",
							'color' => "#ee0000"
					),
					'time' => array (
							'value' => date('Y-m-d H:i:s', time()),
							'color' => '#ee0000'
					),
					'remark' => array (
							'value' => "共有会员:{$param['subCount']}位\n继续加油，邀请更多的朋友们加入吧~~",
							'color' => '#999999'
					)
			);
		}
		empty($data) or $result = $this->wechatAdvance->sendTemplateMessage($accessToken, $openId, $templateId, $data);
		return $result;
	}
	
	
	public function __get( $name ) {
		return $this->data[$name];
	}
	
	public function __set( $name, $value ) {
		$this->data[$name] = $value;
	}
}